package org.xxpay.pay.channel.mfhpay;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.domain.api.AbstractRes;
import org.xxpay.core.common.domain.api.ApiBuilder;
import org.xxpay.core.common.domain.api.PayRes;
import org.xxpay.core.common.domain.api.msg.QueryRetMsg;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.util.XXPayUtil;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;
import org.xxpay.pay.mq.BaseNotify4MchPay;

import java.util.Calendar;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author: pangxiaoyu
 * @date: 2020年2月28日09:10:36
 */
@Service
public class MfhpayPaymentService extends BasePayment {

    @Autowired
    public BaseNotify4MchPay baseNotify4MchPay;

    private static final MyLog _log = MyLog.getLog(MfhpayPaymentService.class);

    @Override
    public String getChannelName() {
        return MfhpayConfig.CHANNEL_NAME;
    }

    /**
     * 支付
     * @param payOrder
     * @return
     */
    @Override
    public AbstractRes pay(PayOrder payOrder) {
        String channelId = payOrder.getChannelId();
        AbstractRes retObj;
        switch (channelId) {
            case MfhpayConfig.CHANNEL_NAME_ALI_H5 :
                retObj = doPay(payOrder);
                break;
            case MfhpayConfig.CHANNEL_NAME_ALI_QR :
                retObj = doPay(payOrder);
                break;
            default:
                return ApiBuilder.bizError("不支持的渠道[channelId="+channelId+"]");
        }
        return retObj;
    }

    /**
     * 支付
     * @param payOrder
     * @return
     */
    public AbstractRes doPay(PayOrder payOrder) {
        MfhpayConfig mfhpayConfig = new MfhpayConfig(getPayParam(payOrder));
        String payType = mfhpayConfig.getPayType();
        PayRes retObj = ApiBuilder.buildSuccess(PayRes.class);
        DBApplicationConfig dbConfig = getDBApplicationConfig();
        Map<String, Object> paramMap = new TreeMap();
        Calendar cal = Calendar.getInstance();
        // 返回当前系统的UTC时间，具体实现可参看JDK源码
        long currentTimeUTC = cal.getTimeInMillis();
        // 接口类型
        paramMap.put("mch_id", mfhpayConfig.getMchId());
        paramMap.put("ptype", payType);
        paramMap.put("order_sn", payOrder.getPayOrderId());
        paramMap.put("money", AmountUtil.convertCent2Dollar(payOrder.getAmount()+""));
        paramMap.put("goods_desc", payOrder.getBody());
        paramMap.put("client_ip", payOrder.getClientIp());
        paramMap.put("format", "page");
        paramMap.put("time", (currentTimeUTC/1000) + "");
        paramMap.put("notify_url", super.getNotifyUrl(getChannelName(), dbConfig));  // 回调地址
        try {
            // 生成签名
            String sign = MfhUtil.createSign(paramMap, mfhpayConfig.getKey());
            paramMap.put("sign", sign);

            // 请求地址
            String toPayUrl = mfhpayConfig.getReqUrl() + "/?c=Pay&" + XXPayUtil.genUrlParams(paramMap);
            _log.info("{}请求路径:{}, 请求参数:{}", getChannelName(), toPayUrl, paramMap);
            retObj.setPayJumpUrl(toPayUrl);      // 可以通过该地址跳转到支付中心界面完成支付(URL)
            StringBuffer payForm = new StringBuffer();
            payForm.append("<script>window.location.href = '"+toPayUrl+"';</script>");
            retObj.setPayUrl(payForm.toString());
            retObj.setPayMethod(PayConstant.PAY_METHOD_FORM_JUMP);
            int updateCount = commonService.payOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
            _log.info("[{}]更新订单状态为支付中:payOrderId={},payUrl={},payType={},result={}", getChannelName(), payOrder.getPayOrderId(), toPayUrl, payType, updateCount);
            return retObj;
        } catch (Exception e) {
            _log.error(e, "");
            return ApiBuilder.bizError("操作失败!");
        }
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public QueryRetMsg query(PayOrder payOrder) {
        return QueryRetMsg.waiting();  //支付中
    }

}
